<template>
  <div class="main">
    <el-table
      ref="table"
      :header-cell-style="headerCellStyle"
      style="width: 100%"
      :row-key="rowKey"
      :expand-row-keys="expandRowKeys"
      :data="data.table_data"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
      @select="onHandleSelect"
    >
      <el-table-column
        v-if="index"
        type="index"
        label="序号"
        width="60"
      ></el-table-column>
      <el-table-column
        v-if="checkbox"
        type="selection"
        width="40"
      ></el-table-column>
      <el-table-column
        v-for="item in column"
        :key="item.prop"
        :sortable="item.sort"
        :sort-by="item.sortBy"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
      >
        <template v-slot="scope">
          <slot
            v-if="item.type === 'slot'"
            :name="item.slotName"
            :row="scope.row"
          ></slot>
          <component
            v-else
            :is="!item.type ? modules['com-text'] : modules[`com-${item.type}`]"
            :data="scope.row"
            :column="item"
            :prop="item.prop"
          ></component>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-wrap" v-if="pagination">
      <el-pagination
        background
        @current-change="onCurrentChange"
        layout="prev, pager, next"
        :total="total"
        :page-size="limit"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeMount, reactive, ref, watch } from 'vue'
import { httpRequest } from '@/api/common.ts'
import { tableColumn } from '@/components/table/column'
import { useTableAttr } from '@/composables/table'
import { TableInstance } from 'element-plus'

const { modules, headerCellStyle } = useTableAttr()

const props = withDefaults(
  defineProps<{
    rowKey?: string
    column?: tableColumn[]
    list?: Array<any>
    initRequest?: boolean
    index?: boolean
    checkbox?: boolean
    loadBack?: boolean
    pagination?: boolean
    format?: () => any
    url?: string
    method?: string
    reqData?: object
    reqParams?: object
    pageSize?: number
    total?: number
    checkList?: Array<any>
    expandRowKeys?: Array<string>
  }>(),
  {
    rowKey: 'id',
    method: 'get',
    pagination: true,
    pageSize: 10,
  },
)
const data = reactive({
  page: 1,
  table_data: [],
})

const table = ref<TableInstance>()
const limit = computed(() => props.pageSize)

onBeforeMount(() => {
  props.initRequest && getTableList()
})

watch(
  () => props.list,
  (value) => {
    if (value) data.table_data = value
  },
  {
    immediate: true,
  },
)

const $emit = defineEmits<{
  (e: 'loadBack', val: any): void
  (e: 'update:checkList', val: any): void
  (e: 'onCurrentChange', val: number): void
}>()

const getTableList = () => {
  const url = props.url
  if (!url) return false

  const req = { url: url, method: props.method, params: {}, data: {} }
  const { page } = data

  if (props.hasPage && (req.method === 'get' || req.method === 'delete')) {
    req.params = { page, limit }
  }
  if (props.hasPage && (req.method === 'post' || req.method === 'put')) {
    req.data = { page, limit }
  }

  if (JSON.stringify(props.reqData) !== '{}') {
    req.data = { ...props.reqData, ...req.data }
  }

  if (JSON.stringify(props.reqParams) !== '{}') {
    req.params = { ...props.reqParams, ...req.params }
  }

  httpRequest(req).then((resp) => {
    let reqData = resp.data
    if (props.format && typeof props.format === 'function') {
      reqData = props.format(resp.data)
    }
    if (props.isPage) {
      data.table_data = reqData.list
      data.total = reqData.total
    } else {
      data.table_data = reqData
    }
    props.loadBack && $emit('loadBack', resp.data.data)
  })
}

const handleSelectionChange = (value: any) => {
  $emit('update:checkList', value)
}

const onHandleSelect = (selection: any, row: any) => {
  // 如果选中的是父行，则阻止子行的选中状态
  console.log(selection, row, 777)
  //table.value?.clearSelection()
  table.value?.setCurrentRow(row)
  // if (row.children && row.children.length > 0) {
  //   const index = selection.indexOf(row)
  //   console.log(index, 8888)
  //   if (index > -1) {
  //     // 防止选中父行时自动勾选子行
  //     let s = selection.splice(index, 1)
  //     console.log(s, 45)
  //   }
  // }
}

// 远程排序
const sortChange = ({ column, prop, order }) => {
  console.log(column, prop, order)
  const sortBy = column.sortBy
  const orderBy = order
  console.log(sortBy, orderBy)
}

const onCurrentChange = (val: number) => {
  data.page = val
  $emit('onCurrentChange', val)
  getTableList()
}
</script>

<style scoped>
.main {
  background-color: #fff;

  .page-wrap {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>
